<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="药品名称" prop="medicineName">
        <el-input v-model="queryParams.medicineName" placeholder="请输入药品名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="功效" prop="efficacy">
        <el-input v-model="queryParams.efficacy" placeholder="请输入功效" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用量" prop="usageDosage">
        <el-input v-model="queryParams.usageDosage" placeholder="请输入用量" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="分类" prop="classificationId">
        <el-cascader v-model="queryParams.classificationId" :options="classifyOptions" :props="cascaderProps"
          placeholder="请选择分类" clearable style="width: 240px" />
      </el-form-item>

      <el-form-item label="药品单位" prop="medicineUnit">
        <el-input v-model="queryParams.medicineUnit" placeholder="请输入药品单位" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建者" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建者" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">

        <el-select v-model="queryParams.status" placeholder="审核状态" clearable style="width: 240px">
          <!-- 直接写死三个选项 -->
          <el-option label="待审核" :value="0" :key="0" />
          <el-option label="已审核" :value="1" :key="1" />
          <el-option label="驳回" :value="2" :key="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新者" prop="updateBy">
        <el-input v-model="queryParams.updateBy" placeholder="请输入更新者" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="更新时间" prop="updateTime">
        <el-date-picker clearable v-model="queryParams.updateTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:medicine:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:medicine:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:medicine:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:medicine:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="medicineList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="${comment}" align="center" prop="medicineId" /> -->


      <!-- 新增图片预览列 -->
      <el-table-column label="药品图片" align="center" width="120">

        <template slot-scope="scope">
          <el-image v-if="scope.row.imagePreviewUrl" style="width: 50px; height: 50px" :src="scope.row.imagePreviewUrl"
            :preview-src-list="[scope.row.imagePreviewUrl]" fit="cover">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <span v-else>无图片</span>
        </template>
      </el-table-column>

      <el-table-column label="药品名称" align="center" prop="medicineName" />
      <el-table-column label="功效" align="center" prop="efficacy" />
      <el-table-column label="用量" align="center" prop="usageDosage" />
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="库存量" align="center" prop="stockQuantity" />
      <el-table-column label="分类名称" align="center" prop="classificationName" />
      <el-table-column label="药品单位" align="center" prop="medicineUnit" />
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新者" align="center" prop="updateBy" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>



      <!-- 表格中的状态列 -->
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="statusTypeMap[scope.row.status]">
            {{ statusTextMap[scope.row.status] || '未知状态' }}
          </el-tag>
        </template>
      </el-table-column>





      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

        <template slot-scope="scope">

          <el-button size="mini" type="text" icon="el-icon-guide" @click="handleExamine(scope.row)"
            v-hasPermi="['system:medicine:examine']" :disabled="scope.row.status==1">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-guide" @click="handlePreview(scope.row)"
            v-hasPermi="['system:medicine:upimg']">图片上传</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:medicine:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:medicine:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改药品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>


      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="药品名称" prop="medicineName">
          <el-input v-model="form.medicineName" placeholder="请输入药品名称" />
        </el-form-item>
        <el-form-item label="功效" prop="efficacy">
          <el-input v-model="form.efficacy" placeholder="请输入功效" />
        </el-form-item>
        <el-form-item label="用量" prop="usageDosage">
          <el-input v-model="form.usageDosage" placeholder="请输入用量" />
        </el-form-item>

        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入用量" />
        </el-form-item>
        <el-form-item label="库存量" prop="stockQuantity">
          <el-input v-model="form.stockQuantity" placeholder="请输入库存量" />
        </el-form-item>
        <el-form-item label="分类" prop="classificationId">
          <el-cascader v-model="form.classificationId" :options="classifyOptions" :props="cascaderProps"
            placeholder="请选择分类" clearable style="width: 240px" />
        </el-form-item>
        <el-form-item label="药品单位" prop="medicineUnit">
          <el-input v-model="form.medicineUnit" placeholder="请输入药品单位" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 审核对话框 -->
    <el-dialog title="药品审核" :visible.sync="examineOpen" width="500px" append-to-body>
      <el-form ref="examineForm" :model="examineForm" :rules="examineRules" label-width="80px">
        <el-form-item label="当前状态" prop="currentStatus">
          <el-tag :type="getTagType(examineForm.status)">
            {{ getStatusText(examineForm.status) }}
          </el-tag>
        </el-form-item>

        <el-form-item label="审核状态" prop="status">
          <el-select v-model="examineForm.status" placeholder="请选择审核状态" style="width: 100%">
            <el-option label="通过审核" :value="1" />
            <el-option label="驳回申请" :value="2" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item
          label="驳回原因"
          prop="rejectReason"
          v-if="examineForm.status === 2"
        >
          <el-input
            v-model="examineForm.rejectReason"
            type="textarea"
            placeholder="请输入驳回原因"
            :rows="4"
          />
        </el-form-item> -->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitExamine">确 定</el-button>
        <el-button @click="examineOpen = false">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 图片上传对话框 -->
    <el-dialog title="上传药品图片" :visible.sync="uploadVisible" width="30%">
      <el-upload name="file" class="upload-demo" drag :action="uploadUrl" :data="{ medicineId: currentMedicineId }"
        :headers="headers" :on-success="handleUploadSuccess" :before-upload="beforeUpload" :show-file-list="false">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过5MB</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadVisible = false">关 闭</el-button>
      </div>
    </el-dialog>





  </div>


</template>

<script>
import { listMedicine, getMedicine, delMedicine, addMedicine, updateMedicine, listClassify, examineMedicine, importImg } from "@/api/system/medicine";

export default {
  name: "Medicine",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 药品信息表格数据
      medicineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        medicineName: null,
        efficacy: null,
        usageDosage: null,
        stockQuantity: null,
        classificationId: null,
        medicineUnit: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        status: 1,
        imageMd5: null,
        imageDownloadUrl: null,
        imagePreviewUrl: null
      },
      listClassify: {},
      // 新增分类数据及级联配置
      classifyOptions: [],
      cascaderProps: {
        value: 'classificationId',
        label: 'classificationName',
        children: 'children',
        emitPath: false, // 只保留最后一级的值
        checkStrictly: true // 可选任意级
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        medicineName: [
          { required: true, message: "药品名称不能为空", trigger: "blur" }
        ],
        efficacy: [
          { required: true, message: "药品功效不能为空", trigger: "blur" }
        ],
        usageDosage: [
          { required: true, message: "药品用量不能为空", trigger: "blur" }
        ],

        stockQuantity: [
          { required: true, message: "药品库存量不能为空且必须为数字", pattern: /^-?\d+(\.\d+)?$/, trigger: "blur" }

        ],



        price: [
          { required: true, message: "药品库存量不能为空且必须为数字", pattern: /^-?\d+(\.\d+)?$/, trigger: "blur" }

        ],
        medicineUnit: [
          { required: true, message: "药品单位不能为空", trigger: "blur" }
        ],
        classificationId: [
          { required: true, message: "药品分类不能为空", trigger: "blur" }
        ],
      },
      // 新增审核相关数据
      examineOpen: false,
      examineForm: {
        medicineId: null,
        status: null,
        // rejectReason: null
      },
      examineRules: {
        status: [
          { required: true, message: "必须选择审核状态", trigger: "blur" }
        ]
        // rejectReason: [
        //   { required: true, message: "驳回必须填写原因", trigger: "blur" },
        //   { min: 10, message: "至少需要10个字符说明", trigger: "blur" }
        // ]
      },


      // 原有数据...
      uploadVisible: false, // 控制上传弹窗
      currentMedicineId: null, // 当前操作的药品ID
      headers: { // 上传请求头（如果后端需要token）
        Authorization: 'Bearer ' + this.$store.getters.token
      }

    };
  },
  created() {
    this.getList();
    this.getClassify();
  },

  // 在Vue组件中增加计算属性
  computed: {
    statusTypeMap() {
      return {
        0: 'warning',  // 待审核-橙色
        1: 'success',  // 已审核-绿色
        2: 'danger'    // 驳回-红色
      }
    },
    statusTextMap() {
      return {
        0: '待审核',
        1: '已审核',
        2: '驳回'
      }
    },
    uploadUrl() {
      return process.env.VUE_APP_BASE_API + "/system/medicine/importImg/" + this.currentMedicineId
    }
  },
  methods: {
    /** 查询药品信息列表 */
    getList() {
      this.loading = true;
      listMedicine(this.queryParams).then(response => {
        this.medicineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 分类列表
    getClassify() {
      listClassify().then(response => {
        const convert = (items) => {
          return items.map(item => ({
            ...item,
            children: item.lists && item.lists.length ? convert(item.lists) : null
          }));
        };
        this.classifyOptions = convert(response.data);
      });
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        medicineId: null,
        medicineName: null,
        efficacy: null,
        usageDosage: null,
        stockQuantity: null,
        classificationId: null,
        medicineUnit: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        status: 0,
        imageMd5: null,
        imageDownloadUrl: null,
        imagePreviewUrl: null,
        price:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.medicineId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加药品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const medicineId = row.medicineId || this.ids
      getMedicine(medicineId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改药品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.medicineId != null) {
            updateMedicine(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMedicine(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const medicineIds = row.medicineId || this.ids;
      this.$modal.confirm('是否确认删除药品信息编号为"' + medicineIds + '"的数据项？').then(function () {
        return delMedicine(medicineIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    /** 审核按钮操作 */
    //  handleExamine(row) {
    //   this.reset();
    //   const medicineId = row.medicineId || this.ids
    //   getMedicine(medicineId).then(response => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "审核";
    //   });
    // },


    /** 审核按钮操作 */
    handleExamine(row) {
      this.examineForm = {
        medicineId: row.medicineId,
        status: row.status,
        // rejectReason: null
      };
      this.examineOpen = true;
    },

    // 状态变更时清空驳回原因
    // handleStatusChange(val) {
    //   if(val !== 2) {
    //     this.examineForm.rejectReason = null;
    //   }
    // },

    /** 提交审核 */
    submitExamine() {
      this.$refs.examineForm.validate(valid => {
        if (valid) {
          const params = {
            medicineId: this.examineForm.medicineId,
            status: this.examineForm.status,
            // ...(this.examineForm.status === 2 && {
            //   rejectReason: this.examineForm.rejectReason
            // })
          };

          examineMedicine(params).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.examineOpen = false;
            this.getList();
          });
        }
      });
    },

    // 修改状态显示判断（原字符串判断改为数字判断）
    getTagType(status) {
      if (status === 1) return 'success';
      if (status === 0) return 'warning';
      if (status === 2) return 'danger';
      return '';
    },
    getStatusText(status) {
      const map = { 0: '待审核', 1: '已审核', 2: '驳回' };
      return map[status] || '';
    },


    /** 导出按钮操作 */
    handleExport() {
      this.download('system/medicine/export', {
        ...this.queryParams
      }, `medicine_${new Date().getTime()}.xlsx`)
    },

    // 点击图片上传按钮
    handlePreview(row) {
      this.currentMedicineId = row.medicineId
      this.uploadVisible = true
    },

    // 上传前的校验
    beforeUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        this.$message.error('只能上传JPG/PNG格式的图片!')
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB!')
      }
      return isImage && isLt5M
    },

    // 上传成功处理
    handleUploadSuccess(response, file) {
      if (response.code === 200) {
        this.$message.success("图片上传成功")
        this.getList() // 刷新列表显示新图片
        this.uploadVisible = false
      } else {
        this.$message.error(response.msg || "上传失败")
      }
    }






  }
};
</script>


<style>
.upload-demo {
  text-align: center;
}
.el-upload-dragger {
  width: 100%;
  height: 200px;
  line-height: 200px;
}
</style>
